class UndergroundSystem {
HashMap<Integer,Pair<String,Integer>> checkIn;
HashMap<String,Pair<Double,Integer>> log;
public UndergroundSystem() {
checkIn = new HashMap<>();
log = new HashMap<>();
}
public void checkIn(int id, String stationName, int t) {
// check in the customer
checkIn.putIfAbsent(id,new Pair<>(stationName,t));
}
public void checkOut(int id, String stationName, int t) {
Pair<String,Integer> info = checkIn.get(id);
String startStation = info.getKey();
int startTime = info.getValue();
String route = startStation + "->" + stationName;
double tripTime = t - startTime;
if(log.containsKey(route)){
double loggedTime = log.get(route).getKey();
int loggedTrip = log.get(route).getValue();
log.put(route,new Pair<>(tripTime + loggedTime, loggedTrip + 1));
}else{
log.put(route,new Pair<>(tripTime,1));
}
// remove the entry
checkIn.remove(id);
}
public double getAverageTime(String startStation, String endStation) {
// Lookup how many times this journey has been made, and the total time.
String routeKey = startStation + "->" + endStation;
Double totalTime = log.get(routeKey).getKey();
int totalTrips = log.get(routeKey).getValue();
// The average is simply the total divided by the number of trips.
return totalTime / totalTrips;
}
}
/**
* Your UndergroundSystem object will be instantiated and called as such:
* UndergroundSystem obj = new UndergroundSystem();
* obj.checkIn(id,stationName,t);
* obj.checkOut(id,stationName,t);
* double param_3 = obj.getAverageTime(startStation,endStation);
*/
Leetcode 1396
· One min read
